<template>
    <view class="container" :style="{paddingBottom:courseDatail.userBuyed==0?'100rpx':''}">
        <image class="course_banner" mode="aspectFit" :src="courseDatail.banner"></image>
        <view class="course_detail">
            <view class="course_base_data">
                <text class="course_title">{{courseDatail.courseTitle}}</text>
                <view class="course_base_bottom">
                    <text class="chapter_num" v-if="courseDatail.chapterNum>0">{{courseDatail.chapterNum}}章节</text>
                    <text class="dot" v-if="courseDatail.chapterNum>0"> · </text>
                    <text class="class_num">{{courseDatail.sectionCount}}课时</text>
                    <text class="dot">·</text>
                    <text class="update_time">{{courseDatail.endTime}}更新</text>
                </view>
            </view>
            <view style="width: 100%;height: 94rpx;">
                <view class="course_tab" :class="[firstDistance&&(firstDistance<=scroll-50)?'course_tab fixed':'course_tab']">
                    <view class="course_tab_item" v-for="(item,index) in tabList" :key="index" @tap="selectTab(index)">
                        <view class="course_tab_item_data">
                            <text class="course_tab_item_name" :class="[index==curIndex?'name_active':'']">{{item.name}}</text>
                            <text class="course_tab_item_active" :style="'background:linear-gradient(180deg,'+(secondColor||'#fff')+' 0%,'+(defaultColor||'#fff')+' 100%)'" v-if="index==curIndex"></text>
                        </view>
                    </view>
                </view>
            </view>
            <block v-if="curIndex==0">
                <view class="course_blcok">
                    <view class="main_servant_title">
                        <text class="title_name">授课老师</text>
                        <text class="main_servant_num">1名</text>
                    </view>
                    <view class="main_servant_list">
                        <scroll-view scroll-x class="tab-h">
                          <view v-for="(item,index) in 1" :key="index"  class='tab-item'>
                            <image class="main_servant_img" :src="courseDatail.mainServantIcon"></image>
                            <view class="main_servant_right">
                                <text class="main_servant_name">{{courseDatail.mainServantName}}</text>
                                <text class="main_servant_describe">{{courseDatail.mainServantTip||'授课老师授课老师授课老师授课老师授课老师授课老师授课老师授课老师授课老师授课老师授课老师授课老师授课老师授课老师授课老师授课老师师授课老师授课老师授课老师授课老师授课老师授课老师授课老师'}}</text>
                            </view>
                          </view>
                        </scroll-view>
                    </view>
                </view>
                <view class="course_blcok">
                    <view class="course_tags_title">
                        <text class="title_name">服务</text>
                    </view>
                    <view class="course_tags_list">
                        <view class="course_tags_item" v-for="(item,index) in courseDatail.tagArray" :key="index">
                            <image :style="{background:defaultColor}" class="course_tags_icon" src="https://image1.sansancloud.com/xianhua/2020_2/27/17/12/31_722.jpg?x-oss-process=style/preview_120"></image>
                            <text class="course_tags_name">{{item}}</text>
                        </view>
                    </view>
                </view>
                <view class="course_blcok">
                    <text class="title_name">课程详情</text>
                    <view class="course_rich">
                        <rich-text-component :receiveData="articleJsonData" v-if="articleJsonData"></rich-text-component>
                    </view>
                </view>
            </block>
            <block v-else>
                <view class="course_table">
                    <view class="course_table_title">
                        <view class="course_table_title_left">
                            <text class="">{{courseDatail.sectionCount}}节课</text>
                            <text class="dot" v-if="courseDatail.coursewareNum!=0"> · </text>
                            <text class="" v-if="courseDatail.coursewareNum!=0">{{courseDatail.coursewareNum}}课件</text>
                        </view>
                        <view class="course_table_title_right">
                            <view class="course_table_fun_item" v-for="(item,indexTwo) in courseTableFunList" :key="indexTwo" @tap="selectFunBtn(indexTwo)">
                                <text class="item_name" v-if="item.state==0">{{item.name}}</text>
                                <text class="item_name" v-else>{{item.nameTwo}}</text>
                                <image class="item_img" :src="item.img" v-if="item.state==0"></image>
                                <image class="item_img" :src="item.imgTwo" v-else></image>
                            </view>
                        </view>
                    </view>
                    <view class="course_table_content">
                        <view class="course_table_chapters_list" v-if="courseDatail.chapters.length!=0">
                            <view class="course_table_chapters_item" v-for="(item,index) in courseDatail.chapters||1" :key="index">
                                <view class="course_table_chapters_item_info" @tap="putOrUpChapterFun(index)">
                                    <text class="chapters_item_line" v-if="item.state==1"></text>
                                    <view class="course_table_chapters_left">
                                        <image class="course_table_chapters_item_icon" src="https://image1.sansancloud.com/xianhua/2020_2/28/11/6/10_736.jpg?x-oss-process=style/preview_120"></image>
                                    </view>
                                    <view class="course_table_chapters_right">
                                        <text class="course_table_chapters_name">{{item.title}}</text>
                                    </view>
                                </view>
                                <view class="course_table_sections_list" v-if="item.state==1">
                                    <view class="course_table_sections_item" v-for="(itemTwo,indexTwo) in item.sections" :key="indexTwo" :data-url="'section_detail.html?sectionId='+itemTwo.id" @tap="tolinkUrl">
                                        <text v-if="indexTwo+1==item.sections.length" class="sections_item_line last_line"></text>
                                        <text v-else class="sections_item_line"></text>
                                        <!-- <text :class="[indexTwo+1==item.sections.length?'sections_item_line last_line':'sections_item_line']"></text> -->
                                        <image class="course_table_sections_item_icon" v-if="itemTwo.contentType==1" src="https://image1.sansancloud.com/xianhua/2020_3/3/9/42/34_92.jpg?x-oss-process=style/preview_120"></image>
                                        <image class="course_table_sections_item_icon" v-if="itemTwo.contentType==2" src="https://image1.sansancloud.com/xianhua/2020_2/28/11/6/10_728.jpg?x-oss-process=style/preview_120"></image>
                                        <image class="course_table_sections_item_icon" v-if="itemTwo.contentType==3" src="https://image1.sansancloud.com/xianhua/2020_2/28/11/6/10_717.jpg?x-oss-process=style/preview_120"></image>
                                        <image class="course_table_sections_item_icon" v-if="itemTwo.contentType==4" src="https://image1.sansancloud.com/xianhua/2020_2/28/11/6/10_703.jpg?x-oss-process=style/preview_120"></image>
                                        <view class="course_table_sections_item_right">
                                            <view class="course_table_sections_item_info">
                                                <text class="course_table_sections_name">{{itemTwo.title}}</text>
                                                <view class="course_table_sections_bottom">
                                                    <text class="course_table_sections_courseware" :style="{background:defaultColor}" v-if="itemTwo.courseware.count!=0">课件</text>
                                                    <text class="course_table_sections_type" v-if="itemTwo.contentType==1">视频</text>
                                                    <text class="course_table_sections_type" v-if="itemTwo.contentType==2">直播</text>
                                                    <text class="course_table_sections_type" v-if="itemTwo.contentType==3">音频</text>
                                                    <text class="course_table_sections_type" v-if="itemTwo.contentType==4">图文</text>
                                                    <text></text>
                                                </view>
                                            </view>
                                            <image v-if="itemTwo.userBuyed==0" class="course_table_sections_item_state_icon" src="https://image1.sansancloud.com/xianhua/2020_2/28/15/5/22_478.jpg?x-oss-process=style/preview_120"></image>
                                        </view>
                                    </view>
                                </view>
                            </view>
                        </view>
                        <view class="noproduct" v-else>
                          <image mode="widthFix" src='https://image1.sansancloud.com/xianhua/2019_12/16/15/54/55_950.jpg?x-oss-process=style/preview_120'></image>
                          <text>没有相关课程</text>
                        </view>
                    </view>
                </view>
            </block>
        </view>
        <view class="course_btn_list" v-if="courseDatail.userBuyed==0">
            <!-- <view class="try_learn_btn">
                <image src="" class="try_learn_btn_icon"></image>
                <text>试学</text>
            </view> -->
            <view class="add_course_btn" @tap="loginStateFun(courseDatail.id)" :style="{background:defaultColor}">
                <text class="add_course_btn_text">加入课程</text>
                <text class="add_course_price">￥{{courseDatail.coursePrice}}</text>
            </view>
        </view>
    </view>
</template>

<script>
import { socketFun } from "../../wxcomponents/public/json2Form";
export default {
  data() {
    return {
      courseDatail:null,
      secondColor:'',
      defaultColor:'',
      setting:null,
      params:{},
      curIndex:1,
      scroll:0,
      firstDistance:'',
      articleJsonData:'',
      tabList:[
          {name:'介绍',index:0},
          {name:'课程表',index:1},
      ],
      courseTableFunIndex:0,
      courseTableFunList:[
          {
              name:'收起',
              nameTwo:'展开',
              state:0,
              img:'https://image1.sansancloud.com/xianhua/2020_2/27/18/34/10_788.jpg?x-oss-process=style/preview_120',
              imgTwo:'https://image1.sansancloud.com/xianhua/2020_2/27/18/34/10_820.jpg?x-oss-process=style/preview_120',
          },
          {
              name:'倒序',
              nameTwo:'正序',
              state:0,
              img:'https://image1.sansancloud.com/xianhua/2020_2/27/18/34/59_796.jpg?x-oss-process=style/preview_120',
              imgTwo:'https://image1.sansancloud.com/xianhua/2020_2/27/18/34/59_796.jpg?x-oss-process=style/preview_120',
          }
      ]
    };
  },
  props: {},

  /*onload*/
  onLoad: function (options) {
    let that=this;
    console.warn("======onLoad:options======", options, getApp().globalData.setting);
    that.params=options;
    that._observer = wx.createIntersectionObserver(that)
    that._observer.relativeTo('.course_tab').observe('.course_tab_item', (res) => {
        console.log("====firstDistance====",res)
        if (!that.firstDistance) {
          that.setData({
            firstDistance: res.boundingClientRect.top,
          })
        }
    })
    that.getCourseData(options);
  },
  onReady: function () {
    
  },
  onShow: function () {
    let that=this;
	that.setData({
        setting:getApp().globalData.setting,
        defaultColor:getApp().globalData.setting.platformSetting.defaultColor,
        secondColor:getApp().globalData.setting.platformSetting.secondColor,
       })
  },
  /* 分享 app.js862行*/
  onShareAppMessage: function () {
    console.log(getApp().globalData.miniIndexPage);
    return getApp().globalData.shareForFx2(getApp().globalData.miniIndexPage);
  },
  onPullDownRefresh: function () {
    let that = this; // 下拉刷新的时候首先判断存不存在tab
    console.log("下拉");
    that.getCourseData(that.params);
    wx.stopPullDownRefresh();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log('===onReachBottom====');
    let that = this
    // if (that.listPage.totalSize > that.listPage.page * that.listPage.pageSize) {
    //   that.listPage.page++
    //   that.getData(that.listPage,'upload');
    // }else{
    //     wx.showToast({
    //       title: "到底了~",
    //       image: '/wxcomponents/images/icons/tip.png',
    //       duration: 1000
    //     });
    // }
  },
  onPageScroll: function (object) {
      let that=this;
      that.setData({
        scroll: object.scrollTop
      })
  },
  methods: {
    loginStateFun:function(courseId){
        let that=this;
        if (getApp().globalData.loginUser && getApp().globalData.loginUser.platformUser.id) {
          that.confirmReserve(courseId)
        } else {
          wx.showModal({
            title: '提示',
            content: '您还未登录，请先登入~',
            success: function (res) {
              if (res.confirm) {
                  getApp().globalData.addLoginListener(that);
                  let url='login.html?url=';
                  let backUrl='course_detail.html?instanceId='+that.params.instanceId;
                  url+= encodeURIComponent(backUrl)
                  getApp().globalData.linkEvent(url)
              } else if (res.cancel) {}
            }
          });
        }
    },
    /* 确认预定课程 */
    confirmReserve: function (courseId) {
      console.log("=====confirmReserve========",courseId);
      let that = this;
      let params = {
        instanceId : courseId,
      };
      var customIndex = getApp().globalData.AddClientUrl('/wx_create_course_pay_order.html', params, 'post');
      getApp().globalData.showToastLoading('loading', true);
      wx.request({
        url: customIndex.url,
        data: customIndex.params,
        header: getApp().globalData.headerPost,
        method: 'POST',
        success: function (res) {
          console.log("=====confirmReserve_res======", res.data);

          if (res.data.errcode == 0) {
              let url='edit_order.html?orderNo=' + res.data.relateObj.orderNo
              that.tolinkUrl(url)
            // wx.navigateTo({
            //   url: '/pages/edit_order/index?orderNo=' + res.data.relateObj.orderNo
            // });
          }

          wx.hideLoading();
        },
        fail: function (res) {
          console.log("fail");
          wx.hideLoading();
          getApp().globalData.loadFail();
        },
        complete: function () {}
      });
    },
    putOrUpChapterFun:function(index){
        console.log("===putOrUpChapterFun===",index)
        let that=this;
        let putCount=0
        let courseData=that.courseDatail;
        let itemData=that.courseTableFunList[0];
        if(courseData.chapters[index].state==0){
            courseData.chapters[index].state=1;
        }else{
            courseData.chapters[index].state=0;
        }
        for(let i=0;i<courseData.chapters.length;i++){
            if(courseData.chapters[i].state==0){
                putCount++
            }
        }
        if(putCount==courseData.chapters.length){
            itemData.state=1;
        }else if(putCount==0){
            itemData.state=0;
        }
        that.courseTableFunList.splice(0,1,itemData)
        that.$set({courseDatail:courseData})
    },
    selectFunBtn:function(index){
        let that=this;
        let courseData=that.courseDatail;
        let itemData=that.courseTableFunList[index];
        console.log("===selectFunBtn==",index,itemData)
        if(itemData.state==0){
            itemData.state=1
            if(index==0){
               for(let i=0;i<courseData.chapters.length;i++){
                   courseData.chapters[i].state=0;
               }
            }else{
               courseData.chapters.reverse();
            }
        }else{
            itemData.state=0;
            if(index==0){
                for(let i=0;i<courseData.chapters.length;i++){
                    courseData.chapters[i].state=1;
                }
            }else{
                courseData.chapters.reverse();
            }
        }
        that.$set({courseDatail:courseData})
        that.courseTableFunList.splice(index,1,itemData)
    },
    selectTab:function(index){
        let that=this;
        that.curIndex=index
    },
    f:function(x){
        let that=this;
        if(x<=1){
            return 3
        }else if(x<=2){
            return 5
        }else{
            return that.f(x-1)*that.f(x-2)
        }
    },
    /* 获取数据 */
    getCourseData: function (params) {
      var that = this
      var customIndex = getApp().globalData.AddClientUrl("/wx_get_course_instance_detail.html", params)
      getApp().globalData.showToastLoading('loading', true)
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          wx.hideLoading()
          console.log(res.data)
          let data=res.data.relateObj
          if (!data ) {
            that.setData({ courseDatail: {} })
          } else {
             let classNum=0;
             let chapterNum=0;
             let coursewareNum=0;
             if(data.chapters){
                 chapterNum=data.chapters.length
             }
             data.chapterNum=chapterNum
             data.endTime=data.endTime.slice(0,11)
             data.startTime=data.startTime.slice(0,11)
             if (data.tags && data.tags != '') {
               let tagArray = data.tags.slice(1, -1).split("][")
               data.tagArray = tagArray;
             }
             let articleJsonData='';
             if (data.content) {
                articleJsonData=data.content;
             }else{
                 articleJsonData=data.course.content||''
             }
             console.log('====articleJsonData====', articleJsonData);
            that.setData({
              articleJsonData: {jsonData:{content:articleJsonData}}
            });
            if(data.chapters){
                for(let i=0;i<data.chapters.length;i++){
                    data.chapters[i].state=1;
                }
            }else{
                data.chapters=[{
                    title:'默认章节',
                    sections:data.sections||[],
                    state:1
                }]
            }
            console.log("data.chapters",data.chapters)
            for(let i=0;i<data.chapters.length;i++){
                for(let j=0;j<data.chapters[i].sections.length;j++){
                    if(data.chapters[i].sections[j].courseware){
                        data.chapters[i].sections[j].courseware=JSON.parse(data.chapters[i].sections[j].courseware)
                        coursewareNum+=data.chapters[i].sections[j].courseware.count
                    }
                }
            }
            data.coursewareNum=coursewareNum
            that.setData({ courseDatail: data })
          }
          wx.hideLoading()
        },
        fail: function (res) {
          console.log("fail")
          wx.hideLoading()
          getApp().globalData.loadFail()
        }
      })
    },
    /* 组件事件集合 */
    tolinkUrl: function (e) {
      console.warn("=======e=======", e);
      let linkUrl = e.currentTarget?e.currentTarget.dataset.url:e;
      getApp().globalData.linkEvent(linkUrl);
    },
    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style scoped>
@import "./index.css";
</style>